<?php
  /**
   * @author EVANDRO DE OLIVEIRA.
   * @category MODEL
   * @package MODELS.
   * @since 17/03/2012.
   * @last_update 24/03/2012.
   * @copyright 2012.
   * @version 1.0.
   *
   */
  class Application_Model_ControlAccess extends Zend_Db_Table_Abstract{
    /* Seta a tabela a ser usada*/
    protected function _setup(){
      $this->_name = 'controle_acesso';
      
      parent::_setup();
    }
    
    public function getData($intIdFuncionario){
      $strSql = $this->select()
      ->where("idFuncionario = ?", $intIdFuncionario)
      ;
      $objResult = $this->fetchRow($strSql);
      
      return Core_Commons::onLoad($objResult);
    }
    
    public function startingWork($intIdFuncionario, $strDsIp){
    	$objResult = $this->getData($intIdFuncionario);
    	if(!$objResult){
        $arrData['idFuncionario']     = $intIdFuncionario; 
        $arrData['dt_login_atual']    = date("Y-m-d H:i:s");
        $arrData['ds_ultimo_ip']      = $strDsIp;
        $arrData['dt_ultima_acao']    = date("Y-m-d H:i:s");
        
        $boolResult = $this->insert($arrData);
      }  
      else{
      	$arrData['dt_login_atual']    = date("Y-m-d H:i:s");
        $arrData['dt_ultimo_login']   = $objResult->dt_login_atual; 
        $arrData['ds_ultimo_ip']      = $strDsIp;
        $arrData['dt_ultima_acao']    = date("Y-m-d H:i:s");
        
        $boolResult = $this->update($arrData, 'idFuncionario = ' . $intIdFuncionario);
      }
      return Core_Commons::onLoad($boolResult);
    }
    
    public function finishingWork($intIdFuncionario, $strDsIp){
      $objResult = $this->getData($intIdFuncionario);
      
      $arrData['ds_ultimo_ip']      = $strDsIp;
      $arrData['dt_ultimo_logout']  = date("Y-m-d H:i:s");
      $arrData['dt_ultima_acao']    = date("Y-m-d H:i:s");
      
      if($this->update($arrData, "idFuncionario = " . $intIdFuncionario))
        return true;
      else
        return false;  
    }
    
    /**
     * 
     * @param $intIdFuncionario
     */
    public function verifyTimeAction($intIdFuncionario, $strTimeExpiration){
    	$arrResult = $this->getData($intIdFuncionario);
    	$strTimestamp = strtotime($arrResult->dt_ultima_acao . "+ " . $strTimeExpiration);
    	$strLimitDate = date('Y-m-d H:i:s', $strTimestamp);
    	
    	if(!Core_ValidaFormulario::validDatesFromDatabase($strLimitDate, date('Y-m-d H:i:s')))
    		return false;
    	
    	return true;
    }
    
    public function updateAction($intIdFuncionario){
      $arrData['dt_ultima_acao']    = date("Y-m-d H:i:s");
      if($this->update($arrData, "idFuncionario = " . $intIdFuncionario))
        return true;
      else
        return false;	
    }
  }